package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    //切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pointCutAspect(){}

    @Before("pointCutAspect()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段的自动填冲。");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        //实体对象作为第一个参数
        //判断获取的参数是否为空。为空则返回。

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0)
            return;
        //获取第一个要进行增强的参数对象。
        Object entry = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseContext.getCurrentId();


        if (operationType.equals(OperationType.INSERT)){
            try {
                Method createTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method createUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method updateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method updateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                createTime.invoke(entry,now);
                createUser.invoke(entry,userId);
                updateTime.invoke(entry,now);
                updateUser.invoke(entry,userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //如果类型是更新操作的话就可以直接
        if (operationType.equals(OperationType.UPDATE)){
            try {
                Method updateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method updateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                updateTime.invoke(entry,now);
                updateUser.invoke(entry,userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
